package com.chagee.store.operation.server.event.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chagee.store.operation.api.bo.OrderExtJsonBO;
import com.chagee.store.operation.api.enums.OrderAcceptanceEnum;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.api.request.OrderPenalizeMoneyRequest;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.model.bo.WorkOrderDetailBO;
import com.chagee.store.operation.server.model.param.QueryWorkOrderDetailParam;
import com.chagee.store.operation.server.model.param.ScanCodePlaceOrderParam;
import com.chagee.store.operation.server.model.param.StoreAppSweepQueryParam;
import com.chagee.store.operation.server.model.param.SupplierWorkOrderQueryParam;
import com.chagee.store.operation.server.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName WorkOrderBaseService  //类名称
 * @Description: 类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/2/26 17:25	//创建时间
 * @UpdateUser: Jacky-zhan
 * @UpdateDate: 2024/2/26 17:25	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkOrderBaseService extends ServiceImpl<WorkOrderMapper, WorkOrderDO> {

	@Value("${pushEmail.endDate:01:00:00}")
	private String pushEmailEndDate;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Value("${pushEndDate.endDate:01:00:00}")
	private String pushEndDate;

	public List<WorkOrderDetailBO> selectOrders(Long id) {
		String yearsDate = DateUtil.yesterDay();
		String endDate = DateUtil.format(new Date(), DateUtil.DEFAULT_DATE_PATTERN).concat(StringUtils.SPACE).concat(pushEmailEndDate);
//		LambdaQueryChainWrapper<WorkOrderDO> storeQuery = lambdaQuery();
//		storeQuery.in(WorkOrderDO::getDocumentStatus, Arrays.asList(StoreWorkOrderStatusEnum.PENDING_ORDERS.getType(),StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType()))
//			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO)
//			.gt(WorkOrderDO::getId, id)
//			.gt(WorkOrderDO::getCreateTime, yearsDate)
//			.le(WorkOrderDO::getCreateTime, endDate)
//			.orderByAsc(WorkOrderDO::getId)
//			.last(CommonConstant.LIMIT_SIZE_SQL);
		QueryWorkOrderDetailParam param = new QueryWorkOrderDetailParam();
		param.setStartIndex(id);
		param.setStartDate(yearsDate);
		param.setEndDate(endDate);

		List<WorkOrderDetailBO> workOrderDetailBOS = baseMapper.queryOrderList(param);
		return workOrderDetailBOS;
	}

	/**
	 * 根据id查询工单信息
	 *
	 * @param workOrderId 工单id
	 * @return 工单信息
	 */
	public WorkOrderDO selectById(Long workOrderId) {
		return workOrderMapper.selectById(workOrderId);
	}

	/**
	 * 根据门店编号查询工单
	 *
	 * @param scanCodePlaceOrderParam 入参
	 * @return 出参
	 */
	public List<WorkOrderDO> queryWorkOrder(ScanCodePlaceOrderParam scanCodePlaceOrderParam) {
		/*LambdaQueryChainWrapper<WorkOrderDO> workOrderDOLambdaQueryChainWrapper = lambdaQuery();
		workOrderDOLambdaQueryChainWrapper
			.eq(StringUtils.isNotBlank(scanCodePlaceOrderParam.getStoreCode()), WorkOrderDO::getStoreCode, scanCodePlaceOrderParam.getStoreCode())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);*/
		return workOrderMapper.selectListByCode(scanCodePlaceOrderParam.getStoreCode());
	}

	/**
	 * 获取工单信息
	 *
	 * @param workOrderNumber 工单编码
	 * @return 工单信息
	 */
	public WorkOrderDO dealWorkOrder(String workOrderNumber) {
		return workOrderMapper.dealWorkOrder(workOrderNumber);
	}

	/**
	 * 更新工单信息
	 *
	 * @param workOrderDO 工单对象
	 */
	public void update(WorkOrderDO workOrderDO) {
		workOrderMapper.updateById(workOrderDO);
	}

	/**
	 * 门店本月单据状态详情
	 * @param map
	 * @return
	 */
	public List<WorkOrderDO> selectMonthOrder(Map<Object, String> map) {
		return workOrderMapper.selectMonthOrder(map);
	}

	/**
	 * 门店最近打烊工单日期
	 * @param map
	 * @return
	 */
	public List<WorkOrderDO> queryOrderDate(Map<Object, String> map) {
		return workOrderMapper.queryOrderDate(map);
	}

	/**
	 * 打烊任务工单
	 * @param request
	 * @return
	 */
	public List<WorkOrderDO> selectOrderList(StoreAppSweepQueryParam request){
		return workOrderMapper.selectOrderList(request);
	}

	public List<WorkOrderDO> orderAcceptance(Map<Object, String> map) {
		return workOrderMapper.list(map);
	}

	/**
	 * 通过 工单编号 + 待执行状态 查询工单信息
	 *
	 * @param workOrderNumber 工单编号
	 * @return list
	 */
	public List<WorkOrderDO> selectListByWorkOrderNumber(String workOrderNumber) {
		return workOrderMapper.selectListByWorkOrderNumber(workOrderNumber);
	}

	public List<WorkOrderDO> selectListByDate(String startDate, String endDate, List<String> storeList) {
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		wrapper.ge(WorkOrderDO::getCreateTime, startDate);
		wrapper.le(WorkOrderDO::getCreateTime, endDate);
		wrapper.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		wrapper.in(WorkOrderDO::getStoreCode, storeList);
		return workOrderMapper.selectList(wrapper);
	}

	public void update(OrderPenalizeMoneyRequest request, OrderExtJsonBO penalizeExtBO){
		this.update(
			lambdaUpdate().eq(WorkOrderDO::getWorkOrderNumber, request.getWorkOrderNumber())
				.set(WorkOrderDO::getPenalizeMoney, request.getPenalizeMoney())
				.set(WorkOrderDO::getExtra, JSONObject.toJSON(penalizeExtBO).toString()).getWrapper());
	}

	public Boolean updateOrderInfo(WorkOrderDO workOrderDO){
		return this.update(
			lambdaUpdate().eq(WorkOrderDO::getId, workOrderDO.getId())
				.set(ObjectUtil.isNotEmpty(workOrderDO.getDocumentStatus()), WorkOrderDO::getDocumentStatus,workOrderDO.getDocumentStatus())
				.set(StringUtils.isNotBlank(workOrderDO.getExtra()), WorkOrderDO::getExtra, workOrderDO.getExtra())
				.set(ObjectUtil.isNotEmpty(workOrderDO.getAppealTime()), WorkOrderDO::getAppealTime, workOrderDO.getAppealTime())
				.set(StringUtils.isNotBlank(workOrderDO.getAppealFlag()), WorkOrderDO::getAppealFlag, workOrderDO.getAppealFlag())
				.set(WorkOrderDO::getUpdateTime, new Date()).getWrapper());
	}

	public Boolean updateRefreshSupplierNo(WorkOrderDO workOrderDO){
		return this.update(
			lambdaUpdate().eq(WorkOrderDO::getId, workOrderDO.getId())
				.set(StringUtils.isNotBlank(workOrderDO.getSupplierNo()), WorkOrderDO::getSupplierNo, workOrderDO.getSupplierNo())
				.getWrapper());
	}


	public List<WorkOrderDO> selectByPendingOrders(Long id) {
		String yearsDate = DateUtil.getYearsDate();
		String endDate = DateUtil.format(new Date(), DateUtil.DEFAULT_DATE_PATTERN).concat(StringUtils.SPACE).concat(pushEndDate);
		LambdaQueryChainWrapper<WorkOrderDO> storeQuery = lambdaQuery();
		storeQuery.in(WorkOrderDO::getDocumentStatus, Arrays.asList(StoreWorkOrderStatusEnum.PENDING_ORDERS.getType(),StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType()))
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO)
			.gt(WorkOrderDO::getId, id)
			.gt(WorkOrderDO::getCreateTime, yearsDate)
			.le(WorkOrderDO::getCreateTime, endDate)
			.orderByAsc(WorkOrderDO::getId)
			.last("limit 50");
		return baseMapper.selectList(storeQuery.getWrapper());
	}

	/**
	 * 获取前两天工单
	 * @param id
	 * @return
	 */
	public List<WorkOrderDO> queryOrder(Long id, String storeCode) {
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		wrapper.eq(WorkOrderDO::getStoreCode,storeCode);
		wrapper.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		wrapper.lt(WorkOrderDO::getId, id);
		wrapper.orderByDesc(WorkOrderDO::getId);
		wrapper.last("limit 2");
		return workOrderMapper.selectList(wrapper);
	}


	public LambdaQueryWrapper<WorkOrderDO> builderWrapper(SupplierWorkOrderQueryParam workOrderRequest) {
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		if (Objects.nonNull(workOrderRequest)) {
			if (CollectionUtil.isNotEmpty(workOrderRequest.getStoreCode())) {
				wrapper.in(WorkOrderDO::getStoreCode, workOrderRequest.getStoreCode());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getStoreName())) {
				wrapper.like(WorkOrderDO::getStoreName, workOrderRequest.getStoreName());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getDocumentStatus())) {
				wrapper.eq(WorkOrderDO::getDocumentStatus, workOrderRequest.getDocumentStatus());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getSupplierNo())) {
				wrapper.eq(WorkOrderDO::getSupplierNo, workOrderRequest.getSupplierNo());
			}

			if (StringUtils.isNotBlank(workOrderRequest.getStartCreateTime())) {
				wrapper.ge(WorkOrderDO::getCreateTime, workOrderRequest.getStartCreateTime());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getEndCreateTime())) {
				wrapper.le(WorkOrderDO::getCreateTime, workOrderRequest.getEndCreateTime());
			}

			if (StringUtils.isNotBlank(workOrderRequest.getCompanyId())) {
				wrapper.eq(WorkOrderDO::getCompanyId, workOrderRequest.getCompanyId());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getIsQualified())) {
				if (OrderAcceptanceEnum.YES.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.ge(WorkOrderDO::getDocumentScore, 80);
				} else if (OrderAcceptanceEnum.NO.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.lt(WorkOrderDO::getDocumentScore, 80);
				}
			}
			wrapper.orderByDesc(WorkOrderDO::getId);
		}
		return wrapper;
	}

	public WorkOrderDO selectWorkOrder(String workOrderNumber) {
		if (StringUtils.isBlank(workOrderNumber)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(WorkOrderDO::getWorkOrderNumber, workOrderNumber)
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<WorkOrderDO> workOrderDOList = workOrderMapper.selectList(wrapper);
		WorkOrderDO workOrderDO = workOrderDOList.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.NO_WORK_ORDER_DATA));

		return workOrderDO;
	}

	public void updateWorkOrder(String orderNumber, OrderExtJsonBO penalizeExtBO) {
		this.update(
			lambdaUpdate().eq(WorkOrderDO::getWorkOrderNumber, orderNumber)
				.set(WorkOrderDO::getExtra, JSONObject.toJSON(penalizeExtBO).toString()).getWrapper());
	}
}
